#!/bin/bash

export AppName=demo-0.0.1.jar

#JVM参数
JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512M -Xmx512M -XX:PermSize=256M -XX:MaxPermSize=512M -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC"

# shellcheck disable=SC2034
APP_HOME=$(pwd)

if [[ "$1" == "" ]]; then
  echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
  exit 1
fi

if [[ "${AppName}" == "" ]]; then
  echo -e "\033[0;31m 未输入应用名 \033[0m"
  exit 1
fi

function start() {
  # shellcheck disable=SC2009
  PID=$(ps -ef | grep java | grep ${AppName} | grep -v grep | awk '{print $2}')

  if [[ x"${PID}" != x"" ]]; then
    echo "${AppName} is running (${PID})"
  else
    fileExist
    nohup java -jar "${JVM_OPTS}" ${AppName} >/dev/null 2>&1 &
    echo "Starting ${AppName}.. SUCCESS!"
  fi
}

# 检查文件是否存在不存在返回
function fileExist() {
  if [[ ! -f "${APP_HOME}/${AppName}" ]]; then
    echo -e -e "\033[0;31m ${APP_HOME} 目录没有 \033[0m \033[0;34m ${AppName} \033[0m"
    exit 1
  fi
}

function stop() {
  echo "Stop ${AppName}"

  PID=""
  query() {
    # shellcheck disable=SC2009
    PID=$(ps -ef | grep java | grep ${AppName} | grep -v grep | awk '{print $2}')
  }

  query
  if [[ x"${PID}" != x"" ]]; then
    kill -TERM "${PID}"
    echo "Shutting down ${AppName}... (pid:${PID})"
    while [[ x"${PID}" != x"" ]]; do
      sleep 1
      query
    done
    echo "SUCCESS!"
  else
    echo "${AppName} already stopped."
  fi
}

function restart() {
  stop
  sleep 2
  start
}

function status() {
  # shellcheck disable=SC2009
  # shellcheck disable=SC2126
  PID=$(ps -ef | grep java | grep ${AppName} | grep -v grep | wc -l)
  if [[ ${PID} != 0 ]]; then
    echo "SUCCESS! ${AppName} running (${PID})"
  else
    echo "ERROR! ${AppName} is not running"
  fi
}

case $1 in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  restart
  ;;
status)
  status
  ;;
*) ;;

esac
